<template>

    <div class="refund-container">
  
      <!-- 搜索表单 -->
  
      <el-card class="search-card">
  
        <el-form :inline="true" :model="queryParams" class="search-form">
  
          <el-form-item label="订单号">
  
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable />
  
          </el-form-item>
  
          <el-form-item label="支付状态">
  
            <el-select v-model="queryParams.status" placeholder="全部" clearable>
  
              <el-option label="待支付" value="PENDING" />
  
              <el-option label="已支付" value="SUCCESS" />
  
              <el-option label="已退款" value="REFUNDED" />
  
            </el-select>
  
          </el-form-item>
  
          <el-form-item label="支付时间">
  
            <el-date-picker
  
              v-model="dateRange"
  
              type="daterange"
  
              range-separator="至"
  
              start-placeholder="开始日期"
  
              end-placeholder="结束日期"
  
              value-format="YYYY-MM-DD"
  
              @change="handleDateChange"
  
            />
  
          </el-form-item>
  
          <el-form-item>
  
            <el-button type="primary" @click="handleQuery">查询</el-button>
  
            <el-button @click="resetQuery">重置</el-button>
  
          </el-form-item>
  
        </el-form>
  
      </el-card>
  
  
  
      <!-- 数据表格 -->
  
      <el-card class="table-card">
  
        <el-table 
  
          v-loading="loading" 
  
          :data="paymentList" 
  
          border
  
          style="width: 100%"
  
        >
  
          <el-table-column label="订单号" prop="orderNo" min-width="180" />
  
          <el-table-column label="支付金额" prop="totalAmount" min-width="120">
  
            <template #default="{ row }">
  
              ¥{{ row.totalAmount }}
  
            </template>
  
          </el-table-column>
  
          <el-table-column label="预约时间" prop="appointmentTime" min-width="180" />
  
          <el-table-column label="咨询师" prop="counselorName" min-width="120" />
  
          <el-table-column label="支付状态" prop="paymentStatus" min-width="120" align="center">
  
            <template #default="{ row }">
  
              <el-tag :type="getStatusType(row.paymentStatus)">
  
                {{ getStatusLabel(row.paymentStatus) }}
  
              </el-tag>
  
            </template>
  
          </el-table-column>
  
          <el-table-column label="操作" width="150" fixed="right" align="center">
  
            <template #default="{ row }">
  
              <template v-if="!row.refundStatus">
  
                <el-button 
  
                  v-if="row.paymentStatus === 'SUCCESS'"
  
                  type="primary" 
  
                  link 
  
                  @click="handleRefund(row)"
  
                >申请退款</el-button>
  
              </template>
  
              <template v-else>
  
                <el-tag :type="getRefundStatusType(row.refundStatus)">
  
                  {{ getRefundStatusLabel(row.refundStatus) }}
  
                </el-tag>
  
              </template>
  
            </template>
  
          </el-table-column>
  
        </el-table>
  
  
  
        <!-- 分页组件 -->
  
        <div class="pagination-container">
  
          <el-pagination
  
            v-model:current-page="queryParams.pageNum"
  
            v-model:page-size="queryParams.pageSize"
  
            :total="total"
  
            :page-sizes="[10, 20, 30, 50]"
  
            layout="total, sizes, prev, pager, next, jumper"
  
            @size-change="handleSizeChange"
  
            @current-change="handleCurrentChange"
  
          />
  
        </div>
  
      </el-card>
  
  
  
      <!-- 退款申请弹窗 -->
  
      <el-dialog
  
        v-model="refundVisible"
  
        title="申请退款"
  
        width="500px"
  
      >
  
        <el-form 
  
          ref="refundFormRef"
  
          :model="refundForm"
  
          :rules="refundRules"
  
          label-width="100px"
  
        >
  
          <el-descriptions :column="1" border>
  
            <el-descriptions-item label="订单号">{{ currentRow.orderNo }}</el-descriptions-item>
  
            <el-descriptions-item label="支付金额">¥{{ currentRow.totalAmount }}</el-descriptions-item>
  
            <el-descriptions-item label="预约时间">{{ currentRow.appointmentTime }}</el-descriptions-item>
  
            <el-descriptions-item label="咨询师">{{ currentRow.counselorName }}</el-descriptions-item>
  
          </el-descriptions>
  
  
  
          <el-form-item label="退款原因" prop="reasonType">
  
            <el-select v-model="refundForm.reasonType" placeholder="请选择退款原因" style="width: 100%">
  
              <el-option label="时间冲突，需要取消预约" value="TIME_CONFLICT" />
  
              <el-option label="个人原因，无法赴约" value="PERSONAL_REASON" />
  
              <el-option label="希望更换咨询师" value="CHANGE_COUNSELOR" />
  
              <el-option label="已通过其他方式解决" value="RESOLVED" />
  
              <el-option label="其他原因" value="OTHER" />
  
            </el-select>
  
          </el-form-item>
  
  
  
          <el-form-item label="具体原因" prop="reason">
  
            <el-input
  
              v-model="refundForm.reason"
  
              type="textarea"
  
              :rows="3"
  
              placeholder="请详细说明退款原因"
  
            />
  
          </el-form-item>
  
  
  
          <el-form-item label="联系电话" prop="phone">
  
            <el-input
  
              v-model="refundForm.phone"
  
              placeholder="请输入可联系到您的手机号"
  
            />
  
          </el-form-item>
  
        </el-form>
  
        <template #footer>
  
          <el-button @click="refundVisible = false">取 消</el-button>
  
          <el-button type="primary" @click="submitRefund" :loading="submitting">
  
            确认申请
  
          </el-button>
  
        </template>
  
      </el-dialog>
  
    </div>
  
  </template>
  
  
  
  <script setup lang="ts">
  
  import { ref, onMounted } from 'vue'
  
  import { ElMessage } from 'element-plus'
  
  import { getPaymentList, applyRefund } from '@/api/payment'
  
  import type { PaymentQuery, PaymentRecord } from '@/types/payment'
  
  
  
  const loading = ref(false)
  
  const submitting = ref(false)
  
  const total = ref(0)
  
  const paymentList = ref<PaymentRecord[]>([])
  
  const refundVisible = ref(false)
  
  const currentRow = ref<PaymentRecord>({} as PaymentRecord)
  
  const refundFormRef = ref()
  
  
  
  // 查询参数
  
  const queryParams = ref<PaymentQuery>({
  
    pageNum: 1,
  
    pageSize: 10,
  
    orderNo: '',
  
    status: undefined,
  
    startDate: '',
  
    endDate: ''
  
  })
  
  
  
  // 日期范围
  
  const dateRange = ref<[string, string]>(['', ''])
  
  
  
  // 退款表单
  
  const refundForm = ref({
  
    reasonType: '', // 退款原因类型
  
    reason: '',    // 具体原因说明
  
    phone: ''      // 联系电话
  
  })
  
  
  
  // 退款表单校验规则
  
  const refundRules = {
  
    reasonType: [
  
      { required: true, message: '请选择退款原因', trigger: 'change' }
  
    ],
  
    reason: [
  
      { required: true, message: '请填写具体退款原因', trigger: 'blur' },
  
      { min: 10, max: 200, message: '具体原因长度应在10-200字之间', trigger: 'blur' }
  
    ],
  
    phone: [
  
      { required: true, message: '请输入联系电话', trigger: 'blur' },
  
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  
    ]
  
  }
  
  
  
  // 获取支付列表
  
  const getList = async () => {
  
    loading.value = true
  
    try {
  
      const res = await getPaymentList(queryParams.value)
  
      paymentList.value = res.data.records
  
      total.value = res.data.total
  
    } catch (error) {
  
      console.error('获取支付列表失败:', error)
  
      ElMessage.error('获取支付列表失败')
  
    } finally {
  
      loading.value = false
  
    }
  
  }
  
  
  
  // 处理退款申请
  
  const handleRefund = (row: PaymentRecord) => {
  
    currentRow.value = row
  
    refundForm.value = {
  
      reasonType: '',
  
      reason: '',
  
      phone: ''
  
    }
  
    refundVisible.value = true
  
  }
  
  
  
  // 提交退款申请
  
  const submitRefund = async () => {
  
    if (!refundFormRef.value) return
  
    
  
    await refundFormRef.value.validate(async (valid: boolean) => {
  
      if (!valid) return
  
      
  
      try {
  
        submitting.value = true
  
        await applyRefund({
  
          orderNo: currentRow.value.orderNo,
  
          amount: currentRow.value.totalAmount,
  
          reasonType: refundForm.value.reasonType,
  
          reason: refundForm.value.reason,
  
          phone: refundForm.value.phone
  
        })
  
        
  
        ElMessage.success('退款申请提交成功')
  
        refundVisible.value = false
  
        getList()
  
      } catch (error) {
  
        console.error('提交退款申请失败:', error)
  
        ElMessage.error('提交退款申请失败')
  
      } finally {
  
        submitting.value = false
  
      }
  
    })
  
  }
  
  
  
  // 获取支付状态样式
  
  const getStatusType = (status: string | undefined): string => {
  
    if (!status) return 'info'
  
    const typeMap: Record<string, string> = {
  
      'PENDING': 'warning',
  
      'SUCCESS': 'success',
  
      'REFUNDED': 'info',
  
      'CANCELLED': 'danger'
  
    }
  
    return typeMap[status] || ''
  
  }
  
  
  
  // 获取支付状态文本
  
  const getStatusLabel = (status: string | undefined): string => {
  
    if (!status) return '未知'
  
    const labelMap: Record<string, string> = {
  
      'PENDING': '待支付',
  
      'SUCCESS': '已支付',
  
      'REFUNDED': '已退款',
  
      'CANCELLED': '已取消'
  
    }
  
    return labelMap[status] || status
  
  }
  
  
  
  // 获取原因文本
  
  const getReasonText = (reason: string): string => {
  
    const reasonMap: Record<string, string> = {
  
      'TIME_CONFLICT': '时间冲突，需要取消预约',
  
      'PERSONAL_REASON': '个人原因，无法赴约',
  
      'CHANGE_COUNSELOR': '希望更换咨询师',
  
      'RESOLVED': '已通过其他方式解决',
  
      'OTHER': '其他原因'
  
    }
  
    return reasonMap[reason] || reason
  
  }
  
  
  
  // 查询和重置
  
  const handleQuery = () => {
  
    queryParams.value.pageNum = 1
  
    getList()
  
  }
  
  
  
  const resetQuery = () => {
  
    queryParams.value = {
  
      pageNum: 1,
  
      pageSize: 10,
  
      orderNo: '',
  
      status: undefined,
  
      startDate: '',
  
      endDate: ''
  
    }
  
    dateRange.value = ['', '']
  
    getList()
  
  }
  
  
  
  // 分页方法
  
  const handleSizeChange = (val: number) => {
  
    queryParams.value.pageSize = val
  
    getList()
  
  }
  
  
  
  const handleCurrentChange = (val: number) => {
  
    queryParams.value.pageNum = val
  
    getList()
  
  }
  
  
  
  // 日期范围变化
  
  const handleDateChange = (val: [string, string]) => {
  
    if (val) {
  
      queryParams.value.startDate = val[0]
  
      queryParams.value.endDate = val[1]
  
    } else {
  
      queryParams.value.startDate = ''
  
      queryParams.value.endDate = ''
  
    }
  
  }
  
  
  
  // 添加退款状态显示方法
  
  const getRefundStatusLabel = (status: string): string => {
  
    const labelMap: Record<string, string> = {
  
      'PENDING': '审核中',
  
      'APPROVED': '已通过',
  
      'REJECTED': '已拒绝'
  
    }
  
    return labelMap[status] || status
  
  }
  
  
  
  const getRefundStatusType = (status: string): string => {
  
    const typeMap: Record<string, string> = {
  
      'PENDING': 'warning',
  
      'APPROVED': 'success',
  
      'REJECTED': 'danger'
  
    }
  
    return typeMap[status] || ''
  
  }
  
  
  
  onMounted(() => {
  
    getList()
  
  })
  
  </script>
  
  
  
  <style lang="scss" scoped>
  
  .refund-container {
  
    padding: 20px;
  
    
  
    .search-card {
  
      margin-bottom: 20px;
  
      
  
      .search-form {
  
        display: flex;
  
        flex-wrap: wrap;
  
        gap: 10px;
  
      }
  
    }
  
    
  
    .table-card {
  
      .pagination-container {
  
        margin-top: 20px;
  
        padding: 10px 0;
  
        text-align: right;
  
      }
  
    }
  
    
  
    :deep(.el-descriptions) {
  
      margin-bottom: 20px;
  
    }
  
  }
  
  </style> 